package com.moji.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moji.common.base.ApiResult;
import com.moji.common.entity.MyPage;
import com.moji.common.utils.PageUtil;
import com.moji.entity.MjCompanyInfo;
import com.moji.entity.SysRole;
import com.moji.entity.SysUser;
import com.moji.entity.dto.ModifyPasswordDto;
import com.moji.entity.dto.PrOnOffDto;
import com.moji.entity.dto.SysUserDto;
import com.moji.entity.vo.SysUserVo;
import com.moji.enums.MoJiEnumConfig;
import com.moji.mapper.MjCompanyInfoMapper;
import com.moji.mapper.SysRoleMapper;
import com.moji.mapper.SysUserMapper;
import com.moji.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moji.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 人员信息表 服务实现类
 * </p>
 *
 * @author ccl
 * @since 2024-07-20
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private MjCompanyInfoMapper mjCompanyInfoMapper;

    @Resource
    private IdGenerator idGenerator;

    @Override
    public ApiResult add(SysUserDto record) {
        SysUser ccpSystemUser = this.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getLoginId, record.getLoginId()));
        if (ccpSystemUser != null) {
            return ApiResult.failed(ResultCode.USER_HAS_EXIST.getMsg());
        }

        //校验手机号码合法性
        if (StringUtils.isNotEmpty(record.getMobile()) && !CheckUtils.isPhoneLegal(record.getMobile())) {
            return ApiResult.failed(ResultCode.PARAMS_USER_MOBILE_LEGAL.getMsg());
        }
        //校验邮箱合法性
        if (StringUtils.isNotEmpty(record.getEmail()) && !CheckUtils.isEmailLegal(record.getEmail())) {
            return ApiResult.failed(ResultCode.PARAMS_USER_EMAIL_LEGAL.getMsg());
        }

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(SysUser::getUserCode);
        List<SysUser> userCodeList = this.list(wrapper);
        if (!userCodeList.isEmpty()) {
            String userCode = String.format("%06d", Integer.parseInt(userCodeList.get(0).getUserCode()) + 1);
            record.setUserCode(userCode);
        }
        //String userCode = UUID.randomUUID().toString().replaceAll("-", "");
        String md5Password = MD5Util.getMd5("123456").toUpperCase();
        record.setPassword(md5Password);

        record.setPrOnoff(ObjectUtil.isNotEmpty(record.getPrOnoff())?record.getPrOnoff():1);
        String rolesCode = record.getRolesCode();
        String roelsName = "";
        //遍历角色码对应的角色名称，存储到数据库
        if (!StringUtils.isEmpty(rolesCode)) {
            List<String> roleCodeList = Arrays.asList(rolesCode.split(","));
            if (!roleCodeList.isEmpty()) {
                for (String roleCode : roleCodeList) {
                    LambdaQueryWrapper<SysRole> sysRoleWrapper = new LambdaQueryWrapper<>();
                    sysRoleWrapper.eq(SysRole::getRoleCode, roleCode);
                    SysRole sysRole = sysRoleMapper.selectOne(sysRoleWrapper);
                    if (sysRole != null) {
                        roelsName += sysRole.getRoleName() + ",";
                    }
                }
            }
        }
        if (StringUtils.isNotEmpty(roelsName)) {
            record.setRolesName(roelsName.substring(0, roelsName.lastIndexOf(",")));
        }

        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        record.setCreateId(MoJiCommonUtils.getUserCode());
        record.setUpdateId(MoJiCommonUtils.getUserCode());

        return ApiResult.ok(this.save(record));

    }

    @Override
    public ApiResult edit(SysUserDto sysUser) {
        //姓名不能为空
        if (StringUtils.isEmpty(sysUser.getUserName())) {
            return ApiResult.failed(ResultCode.PARAMS_PASSWORD_IS_NULL.getMsg());
        }
        //校验手机号码合法性
        if (StringUtils.isNotEmpty(sysUser.getMobile()) && !CheckUtils.isPhoneLegal(sysUser.getMobile())) {
            return ApiResult.failed(ResultCode.PARAMS_USER_MOBILE_LEGAL.getMsg());
        }
        sysUser.setUpdateTime(new Date());
        sysUser.setUpdateId(MoJiCommonUtils.getUserCode());

        return ApiResult.ok(this.updateById(sysUser));
    }

    @Override
    public boolean delete(Long id) {
        SysUser sysUser = this.getById(id);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在,请核查!");
        }

        return this.removeById(id);
    }

    @Override
    public SysUserVo detail(Long id) {
        SysUserVo sysUserVo=new SysUserVo();
        SysUser sysUser = this.getById(id);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在,请核查!");
        }
        BeanUtils.copyProperties(sysUser,sysUserVo);

        return sysUserVo;
    }

    @Override
    public MyPage<SysUserVo> queryPage(SysUser sysUser) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(sysUser.getUserName())) {
            wrapper.like(SysUser::getUserName, sysUser.getUserName());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getUserCode())) {
            wrapper.like(SysUser::getUserCode, sysUser.getUserCode());
        }
        if (ObjectUtil.isNotEmpty(sysUser.getLoginId())) {
            wrapper.like(SysUser::getLoginId, sysUser.getLoginId());
        }
        PageHelper.startPage(sysUser.getPageNum(), sysUser.getPageSize());
        wrapper.orderByDesc(SysUser::getUpdateTime);
        List<SysUser> userList = this.list(wrapper);
        List<SysUserVo> sysUserVos = new ArrayList<>();
        userList.stream().forEach(one -> {
            SysUserVo sysUserVo=new SysUserVo();
            //角色遍历反显中文名称
            if(ObjectUtil.isNotEmpty(one.getRolesCode())){
                LambdaQueryWrapper<SysRole> roleWrapper=new LambdaQueryWrapper<>();
                roleWrapper.in(SysRole::getRoleCode,
                        Arrays.asList(one.getRolesCode().split(",")));
                List<SysRole> roleList=sysRoleMapper.selectList(roleWrapper);
                StringBuffer rolesName=new StringBuffer();
                if(ObjectUtil.isNotEmpty(roleList)){
                    roleList.stream().forEach(ccpSystemRole -> {
                        rolesName.append(ccpSystemRole.getRoleName()+",");
                    });
                    one.setRolesName(rolesName.substring(0,rolesName.length()-1));
                }
            }
            BeanUtils.copyProperties(one,sysUserVo);

            sysUserVos.add(sysUserVo);
        });
        PageInfo<SysUserVo> info = new PageInfo<>(sysUserVos);
        return PageUtil.PageInfo2MyPage(info);
    }

    @Override
    public boolean updateStatus(PrOnOffDto prOnOffDao) {
        SysUser sysUser = this.getById(prOnOffDao.getId());
        if (sysUser == null) {
            throw new RuntimeException("用户不存在,请核查!");
        }
        sysUser.setPrOnoff(Integer.parseInt(prOnOffDao.getPrOnOff()));

        return this.updateById(sysUser);
    }

    @Override
    public boolean resetPassword(Long id) {
        SysUser sysUser = this.getById(id);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在,请核查!");
        }
        sysUser.setPassword(MD5Util.getMd5("123456").toUpperCase());
        return this.updateById(sysUser);
    }

    @Override
    public boolean modifyPassword(ModifyPasswordDto modifyPasswordDao) {
        String newPassword = modifyPasswordDao.getNewPassword();
        String oldPassword = modifyPasswordDao.getOldPassword();
        String md5NewPassword = MD5Util.getMd5(newPassword).toUpperCase();
        String md5OldPassword = MD5Util.getMd5(oldPassword).toUpperCase();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SysUser::getUserCode, modifyPasswordDao.getUserCode());
        SysUser sysUser = this.getOne(wrapper);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在,请核查!");
        }
        if (sysUser.getPassword().equals(md5OldPassword)) {
            sysUser.setPassword(md5NewPassword);
        }
        return this.updateById(sysUser);
    }

}
